<template>
  <!-- #ifndef MP-WEIXIN -->
  <view class="count-down-btn" :style="`color:${color}`">
    <view class="get-auth-code" :style="`color:${color}`" v-if="countDown <= 0" @click="getAuthCode">{{
      hasGet ? "重新获取验证码" : "获取验证码"
    }}</view>
    <view v-if="countDown > 0" :style="`color:${color}`" class="count-down">{{ countDown }}</view>
  </view>
  <!-- #endif -->

  <!-- #ifdef MP-WEIXIN -->
  <view class="count-down-btn">
    <view class="get-auth-code" v-if="countDown <= 0" @click="getAuthCode">{{
      hasGet ? "重新获取验证码" : "获取验证码"
    }}</view>
    <view v-if="countDown > 0" class="count-down">{{ countDown }}</view>
  </view>
  <!-- #endif -->
</template>

<script>
export default {
  props: {
    color: {
      type: String,
      default: "#345efe",
    },
  },
  data: () => ({
    countDown: 0,
    hasGet: false,
    countDownInterval: null,
  }),
  computed: {},
  methods: {
    /**
     * 获取验证码
     */
    getAuthCode() {
      this.$emit("getAuthCode")
      this.hasGet = true
    },
    /**
     * 开始计时
     */
    beginCountDown(time = 60) {
      console.log("开始计时")
      this.countDown = time

      this.countDownInterval = setInterval(() => {
        this.countDown -= 1

        if (this.countDown <= 0) {
          clearInterval(this.countDownInterval)
        }
      }, 1000)
    },
  },
  watch: {},

  // 组件周期函数--监听组件挂载完毕
  mounted() {},
  // 组件周期函数--监听组件数据更新之前
  beforeUpdate() {},
  // 组件周期函数--监听组件数据更新之后
  updated() {},
  // 组件周期函数--监听组件激活(显示)
  activated() {},
  // 组件周期函数--监听组件停用(隐藏)
  deactivated() {},
  // 组件周期函数--监听组件销毁之前
  beforeDestroy() {
    if (this.countDownInterval) {
      clearInterval(this.countDownInterval)
    }
  },
}
</script>

<style scoped lang="scss">
.count-down-btn {
  width: 220rpx;
  height: 50rpx;
  line-height: 50rpx;
  font-size: 30rpx;
  text-align: center;

  margin-left: 30rpx;

  .get-auth-code {
    width: 100%;
    height: 100%;
    color: #345efe;
    font-weight: bold;
  }

  .get-auth-code:active {
    background-color: #ffffff;
  }

  .count-down {
    background-color: #ffffff;
    color: #345efe;
    font-size: 30rpx;
    font-weight: bold;
    width: 100%;
    height: 100%;
  }
}
</style>
